package com.xiewz.service;

import com.xiewz.pojo.Comment;
import com.xiewz.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class ApiCommentService {
    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private RedisTemplate redisTemplate;

    // 先使用API的方式进行缓存，先去缓存查，没有 再查数据库
    public Comment findCommentById(Integer id) {
        Object o = redisTemplate.opsForValue().get("comment_" + id);
        if(o != null){
            // 缓存中查到就返回
            return (Comment) o;
        }
        // 缓存没有，去数据库查询
        Optional<Comment> comment = commentRepository.findById(id);
        if (comment.isPresent()) {
            Comment comment1 = comment.get();
            //将查询结果存到缓存中，同时还可以设置有效期为1天
            redisTemplate.opsForValue().set("comment_" + id,comment1,1, TimeUnit.DAYS);
            return comment1;
        }
        return null;
    }

   // 更新
    public Comment updateComment(Comment comment){
        commentRepository.updateComment(comment.getAuthor(),comment.getId());
        redisTemplate.opsForValue().set("comment_"+comment.getId(),comment);
        return comment;
    }

    public void deleteComment(Integer id){
        commentRepository.deleteById(id);
        redisTemplate.delete("comment_"+id);

    }


}
